package com.company.project.controller;

import java.io.*;
import java.net.URL;
import java.util.*;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import com.company.project.common.enums.RestCode;
import com.company.project.common.pojo.FileBean;
import com.company.project.common.pojo.FileBeanOss;
import com.company.project.common.pojo.Rest;
import com.company.project.common.utils.RestUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传的Controller
 */
@Controller("UploadController")
@RequestMapping("/upload")
@Scope("prototype")
public class UploadController {

    private static final Log LOG = LogFactory.getLog(UploadController.class);

    @Value("${file-path}")
    private String filePath;

	/**
	 * 多文件上传本地
	 */
	@RequestMapping(value = "/upload-batch", method = RequestMethod.POST)
	@ResponseBody
	public Rest batchUpload(MultipartFile[] files) {
//        String[] urls = new String[files.length];
        List<FileBean> fileBeanList = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            MultipartFile multipartFile = files[i];

            //文件后缀名
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf(".") + 1);
            //文件新名称
            String newFileName = String.valueOf(System.currentTimeMillis() + (int) ((Math.random() * 9 + 1) * 100)) + "@_@" + multipartFile.getOriginalFilename();
            //中间目录
            String middlePath = DateFormatUtils.format(new Date(), "yyyy-MM-dd") + File.separator;
            //全目录
            String fileFullName = filePath + fileClassification(suffix) + File.separator + middlePath + newFileName;
            // 图片访问地址（tomcat服务器）
//            urls[i] = File.separator + fileClassification(suffix) + File.separator + middlePath + newFileName;
            String url = File.separator + fileClassification(suffix) + File.separator + middlePath + newFileName;
            BufferedOutputStream out = null;
            try {
                File file = new File(fileFullName);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                out = new BufferedOutputStream(new FileOutputStream(new File(fileFullName)));
                out.write(multipartFile.getBytes());
                out.flush();

                FileBean fileBean = new FileBean();
                fileBean.setUrl(url);    // 访问地址
                fileBean.setName(multipartFile.getOriginalFilename());
                fileBeanList.add(fileBean);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return RestUtil.rest(RestCode.CODE_200.getCode(), RestCode.CODE_200.getDesc(), fileBeanList);
	}

    /**
     * 多文件上传阿里oss
     */
    @RequestMapping(value = "/upload-batch-oss", method = RequestMethod.POST)
    @ResponseBody
    public Rest batchUploadOSS(MultipartFile[] files, String bucketName) throws IOException {
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI7RDweCFYN01O";
        String accessKeySecret = "xG0haFDFCuVzPwH9cbO51EwrEWaH82";
        String securityToken = "";
        bucketName = bucketName == null ?  "guanyua" : bucketName;
//        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        List<FileBeanOss> fileBeanOssList = new ArrayList<>();
        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                return RestUtil.rest(RestCode.CODE_403.getCode(), "您的Bucket不存在");
//                LOG.info("您的Bucket不存在，创建Bucket：" + bucketName + "。");
//                ossClient.createBucket(bucketName);
            }

            for (int i = 0; i < files.length; i++) {
                MultipartFile multipartFile = files[i];
                if(null != multipartFile){
                    //文件后缀名
                    String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf(".") + 1);
                    //文件新名称
                    String newFileName = String.valueOf(System.currentTimeMillis() + (int) ((Math.random() * 9 + 1) * 100)) + "@_@" + multipartFile.getOriginalFilename();
                    if(!"".equals(multipartFile.getOriginalFilename().trim())){
                        //*****************************上传到OSS*********************************************
                        //OSS中间目录
                        String OSSMiddlePath = DateFormatUtils.format(new Date(), "yyyyMMdd") + "/";
                        // OSS全目录，key
                        String fileKey = fileClassification(suffix) + "/" + OSSMiddlePath + newFileName;

                        ossClient.putObject(new PutObjectRequest(bucketName, fileKey, new ByteArrayInputStream(multipartFile.getBytes())));

                        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);  //10年
                        URL url = ossClient.generatePresignedUrl(bucketName, fileKey, expiration);
                        LOG.info("存入OSS成功，OSS文件地址：" + url.toString());

                        FileBeanOss fileBeanOss = new FileBeanOss();
                        fileBeanOss.setUrl(url.toString());    // oss访问地址
                        fileBeanOss.setName(multipartFile.getOriginalFilename());
                        fileBeanOss.setOssObjectKey(fileKey);
                        fileBeanOssList.add(fileBeanOss);
                    }
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            ossClient.shutdown();
        }

        return RestUtil.rest(RestCode.CODE_200.getCode(), RestCode.CODE_200.getDesc(), fileBeanOssList);
    }

    /**
     * 文件分类
     */
    private String fileClassification(String suffix){
        String[] imageType = {"jpg", "bmp", "gif", "png"};
        String[] audioType = {"wmv", "mp3", "wma", "mp3pro", "mod", "ra", "md", "asf", "aac", "vqf", "mid", "ogg", "m4a", "aac+", "aiff", "au", "cd", "wav", "flac", "ape"};
        String[] videoType = {"avi", "mov", "rmvb", "flv", "rmvb", "flv", "mp4", "3gp", "mkv"};
        String[] documentType = {"doc", "docx", "vsd", "xls", "xlsx", "ppt", "pptx"};

        if(Arrays.asList(imageType).contains(suffix.toLowerCase())){
            return "image";
        } else if(Arrays.asList(audioType).contains(suffix.toLowerCase())) {
            return "audio";
        } else if(Arrays.asList(videoType).contains(suffix.toLowerCase())) {
            return "video";
        } else if (Arrays.asList(documentType).contains(suffix.toLowerCase())){
            return "document";
        } else {
            return "other";
        }
    }

}